// todo: extension 文件
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'enum/language.dart';
import 'gen_l10n/app_localizations.dart';

// const l10nDelegates = AppLocalizations.localizationsDelegates;
// const l10nLocales = AppLocalizations.supportedLocales;

extension AppLocalizationsX on BuildContext {
  AppLocalizations get l10n => AppLocalizations.of(this);
}

class LocaleNotifier extends StateNotifier<Language> {
  LocaleNotifier() : super(Language.en_US) {
    _loadLanguage();
  }

  Future<void> _loadLanguage() async {
    // Initialize SharedPreferences, 初始化存储
    // final prefs = await SharedPreferences.getInstance();
    // final storedLanguage = prefs.getString('language');

    // if (storedLanguage != null) {
    //   state = Language.values.firstWhere(
    //     (language) => language.label == storedLanguage,
    //     orElse: () => Language.en_US,
    //   );
    // } else {
    _setDefaultLanguageBasedOnSystem();
    // }
  }

  void _setDefaultLanguageBasedOnSystem() {
    String locale = PlatformDispatcher.instance.locale
        .toString(); // 系统语言 ,zh_Hans_CN 简体中文，zh-TW，zh-HK，zh-SG
    if (locale.contains('zh')) {
      state = Language.zh_CN;
    } else {
      state = Language.en_US;
    }
  }

  String getLanguage() {
    return state.label;
  }

  Future<void> setLanguage(Language newLanguage) async {
    // print('----laguagage');
    // print(newLanguage);
    state = newLanguage;

    // final prefs = await SharedPreferences.getInstance();
    // await prefs.setString('language', newLanguage.label);
  }
}

// Riverpod provider for LocaleNotifier
final localeProvider = StateNotifierProvider<LocaleNotifier, Language>(
  (ref) => LocaleNotifier(),
);
